#include "i2c_server.h"
#include "i2c/i2c.h"
#include "pico/stdlib.h"
#include "hardware/i2c.h"

#define LOG_TAG "I2C_SERVER"
#include "log/log.h"

// 定义I2C端口和设备地址
#define I2C_SDA_PIN   20
#define I2C_SCL_PIN   21
#define I2C_PORT      i2c0

static void scan_i2c_device(void)
{
    for (int addr = 0; addr < (1 << 7); ++addr) {
        // Perform a 1-byte dummy read from the probe address. If a slave
        // acknowledges this address, the function returns the number of bytes
        // transferred. If the address byte is ignored, the function returns
        // -1.

        // Skip over any reserved addresses.
        int ret;
        UInt8 rxdata;

        ret = i2c_read_blocking(I2C_PORT, addr, &rxdata, 1, False);

        if (ret >= 0)
            LOG_D("device exsits, addr=%02X ret=%d", addr, ret);
    }
}

Bool TI2CServerInit(void)
{
    // 初始化Pico的I2C接口
    i2c_init(I2C_PORT, 400 * 1000); // 设置I2C波特率，这里是400kHz

    // 设置GPIO引脚为I2C功能
    gpio_set_function(I2C_SDA_PIN, GPIO_FUNC_I2C);
    gpio_set_function(I2C_SCL_PIN, GPIO_FUNC_I2C);
    gpio_pull_up(I2C_SDA_PIN);
    gpio_pull_up(I2C_SCL_PIN);

    scan_i2c_device();
}

Bool TI2CServerFini(void)
{

}

Int32 TI2CSendData(const UInt8 addr, const UInt8 *data, Int32 data_len)
{
    return i2c_write_blocking(I2C_PORT, addr, data, data_len, False);
}

Int32 TI2CReadData(const UInt8 addr, UInt8 *buf, Int32 buf_size)
{
    return i2c_read_blocking(I2C_PORT, addr, buf, buf_size, False);
}
